import 'package:dio/dio.dart';

class NetworkService{
  final _dio = Dio();

  NetworkService(){
    _dio.options.baseUrl = 'https://live-api.itheima.net';
    _dio.options.connectTimeout = const Duration(seconds: 18);
    _dio.options.receiveTimeout = const Duration(seconds: 18);
    _dio.options.headers = {
      'Content-Type': 'application/json',
    };
    _addInterceptors();
  }
  // get请求
  Future<dynamic>get(String url,{Map<String,dynamic>? params})async{
    try {
      final response = await _dio.get(url,queryParameters: params);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }
  // post请求
  Future<dynamic> post(String url, {required Map<String, dynamic> data}) async {
    try {
      final response = await _dio.post(url, data: data);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }
  // put请求
      Future<dynamic> put(String url, dynamic data) async {
    try {
      final response = await _dio.put(url, data: data);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }
  // delete请求
      Future<dynamic> delete(String url, dynamic data) async {
    try {
      final response = await _dio.delete(url, data: data);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

    void _addInterceptors() {
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        // 请求拦截器：添加公共请求参数、token 等
        // todo
        return handler.next(options);
      },
      onResponse: (response, handler) {
        // 响应拦截器：统一处理成功响应
        return handler.next(response);
      },
      onError: (DioException error, handler) {
        // 响应拦截器：统一处理错误响应
        return handler.next(error);
      },
    ));
  }


  dynamic handleResponse(Response response) {
    if (response.statusCode! >= 200 && response.statusCode! < 300) {
      return response.data;
    } else {
      throw Exception('请求失败，状态码：${response.statusCode}');
    }
  }

  dynamic handleError(error) {
    if (error is DioException) {
      if (error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.receiveTimeout) {
        throw Exception('网络连接超时');
      } else if (error.type == DioExceptionType.badResponse) {
        throw Exception('响应错误，状态码：${error.response?.statusCode}');
      } else {
        throw Exception('网络请求错误：$error');
      }
    } else {
      throw Exception('未知错误：$error');
    }
  }

}

// 导出
final http = NetworkService();